#include "dice.h"
#include <QPainter>
#include "foregroundscene.h"

/*

  DICE CLASS


  */

Dice::Dice(QGraphicsObject* parent)
    :QGraphicsObject(parent), _side(0)
{

    diceImages = new QList<QPixmap>();
    QPixmap red(":/dice/images/dice_red.png");
    QPixmap yel(":/dice/images/dice_yel.png");
    QPixmap gre(":/dice/images/dice_gre.png");
    QPixmap blu(":/dice/images/dice_blu.png");
    QPixmap bla(":/dice/images/dice_bla.png");
    QPixmap whi(":/dice/images/dice_whi.png");
    QPixmap interval(":/dice/images/dice_int.png");
    diceImages->append(red);
    diceImages->append(interval);
    diceImages->append(yel);
    diceImages->append(interval);
    diceImages->append(gre);
    diceImages->append(interval);
    diceImages->append(blu);
    diceImages->append(interval);
    diceImages->append(bla);
    diceImages->append(interval);
    diceImages->append(whi);
    diceImages->append(interval);

    width = red.width();
    height = red.height();

    anim = new QPropertyAnimation(this, "side", this);
    anim->setStartValue(0);
    anim->setEndValue(12);
    anim->setDuration(600);
    anim->setLoopCount(-1);
    anim->start(QAbstractAnimation::DeleteWhenStopped);

    SceneSensor* s = new SceneSensor(this);
    connect(s, SIGNAL(pressed()), this, SLOT(stop()));
}

Dice::~Dice(){
    //qDebug("ok to delete");
    delete diceImages;
}

QRectF Dice::boundingRect() const{
    return QRectF(-width/2, -height/2, width, height);
}

void Dice::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
    painter->drawPixmap(-width/2, -height/2, diceImages->at(_side));

}

int Dice::getSide(){
    return _side;
}

void Dice::setSide(int s){
    _side = s;
    update();
}


void Dice::stop(){
    anim->stop();
    if(_side%2!=0){
        qsrand(_side);
        setSide(qrand()%6*2);
    }
    emit stopSignal();
}


/*

  DICE MANAGER CLASS

  */


DiceManager::DiceManager(QGraphicsObject* parent)
    :QGraphicsObject(parent), noOfDice(0)
{
}
QRectF DiceManager::boundingRect() const{
    return QRectF(-100, -100, 200, 200);
}

void DiceManager::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){

}
void DiceManager::addDice(){
    Dice* d = new Dice(this);
    connect(d, SIGNAL(stopSignal()), this, SLOT(subDice()));
    d->moveBy(100-noOfDice*100, 0);
    noOfDice++;
}

void DiceManager::subDice(){
    noOfDice--;
    if(noOfDice==0){
        emit finished();
    }
}
